// 设备管理云对象
const crypto = require('crypto');
const UniID = require('uni-id-common')
module.exports = {
	_before: function () {
		// 通用预处理器
		this.startTime = Date.now();
	},

	/**
	 * 获取用户设备列表
	 * @param {string} userId 用户ID
	 * @returns {object} 设备列表
	 */
	async getDeviceList() {

		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const userId = uid
		
		if (code !== 0 || !uid) {
			return {
				errCode: 401,
				errMsg: '用户未登录'
			}
		}
		try {
			const db = uniCloud.database();
			const dbCmd = db.command;
			
			// 获取拥有的设备和被分享的设备
			const deviceResult = await db.collection('sh_user_device').where(
				dbCmd.or([
					{owner_id: userId},
					{shared_users: dbCmd.in([userId])}
				])
			).orderBy('create_time', 'desc').get();

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: deviceResult.data
			}
		} catch (error) {
			console.error('获取设备列表失败:', error);
			return {
				errCode: 'GET_DEVICE_LIST_FAILED',
				errMsg: '获取设备列表失败'
			}
		}
	},

	/**
	 * 添加设备
	 * @param {string} deviceId 设备ID
	 * @param {string} deviceName 设备名称
	 * @param {string} deviceType 设备类型
	 * @param {string} location 设备位置
	 * @returns {object} 添加结果
	 */
	async addDevice({ deviceId, deviceName, deviceType, location}) {

		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const userId = uid
		if (!deviceId || !deviceName) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '必要参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			
			// 检查设备是否已被绑定
			const existDevice = await db.collection('sh_user_device').where({
				device_id: deviceId
			}).get();

			if (existDevice.data.length > 0) {
				return {
					errCode: 'DEVICE_EXISTS',
					errMsg: '设备已被绑定'
				}
			}

			// 添加设备
			const deviceResult = await db.collection('sh_user_device').add({
				device_id: deviceId,
				device_name: deviceName,
				device_type: deviceType || 'pro',
				owner_id: userId,
				shared_users: [],
				device_status: 0,
				location: location || '',
				light_settings: {
					enabled: true,
					brightness: 80,
					color_temperature: 4000
				},
				create_time: new Date(),
				update_time: new Date()
			});

			// 为设备创建默认播放列表
			await db.collection('sh_user_playlist').add({
				device_id: deviceResult.id,
				patterns: [],
				current_index: 0,
				play_mode: 0,
				auto_play: true,
				create_time: new Date(),
				update_time: new Date()
			});

			return {
				errCode: 0,
				errMsg: '设备添加成功',
				data: {
					deviceId: deviceResult.id
				}
			}
		} catch (error) {
			console.error('添加设备失败:', error);
			return {
				errCode: 'ADD_DEVICE_FAILED',
				errMsg: '添加设备失败'
			}
		}
	},

	/**
	 * 更新设备信息
	 * @param {string} deviceId 设备ID
	 * @param {object} deviceInfo 设备信息
	 * @returns {object} 更新结果
	 */
	async updateDevice({deviceId, deviceInfo}) {

		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const userId = uid
		if (!deviceId || !userId || !deviceInfo) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			
			// 检查设备权限
			const deviceResult = await db.collection('sh_user_device').doc(deviceId).get();
			if (deviceResult.data.length === 0) {
				return {
					errCode: 'DEVICE_NOT_FOUND',
					errMsg: '设备不存在'
				}
			}

			const device = deviceResult.data[0];
			if (device.owner_id !== userId) {
				return {
					errCode: 'NO_PERMISSION',
					errMsg: '无权限操作此设备'
				}
			}

			// 过滤允许更新的字段
			const allowedFields = ['device_name', 'location', 'light_settings'];
			const updateData = {};
			
			allowedFields.forEach(field => {
				if (deviceInfo[field] !== undefined) {
					updateData[field] = deviceInfo[field];
				}
			});
			
			updateData.update_time = new Date();

			await db.collection('sh_user_device').doc(deviceId).update(updateData);

			return {
				errCode: 0,
				errMsg: '设备更新成功'
			}
		} catch (error) {
			console.error('更新设备失败:', error);
			return {
				errCode: 'UPDATE_DEVICE_FAILED',
				errMsg: '更新设备失败'
			}
		}
	},

	/**
	 * 删除设备
	 * @param {string} deviceId 设备ID
	 * @param {string} userId 用户ID
	 * @returns {object} 删除结果
	 */
	async deleteDevice({deviceId}) {

		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const userId = uid
		if (!deviceId) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			
			// 检查设备权限
			const deviceResult = await db.collection('sh_user_device').doc(deviceId).get();
			if (deviceResult.data.length === 0) {
				return {
					errCode: 'DEVICE_NOT_FOUND',
					errMsg: '设备不存在'
				}
			}

			const device = deviceResult.data[0];
			if (device.owner_id !== userId) {
				return {
					errCode: 'NO_PERMISSION',
					errMsg: '只有设备拥有者才能删除设备'
				}
			}

			// 删除相关数据
			await Promise.all([
				db.collection('sh_user_device').doc(deviceId).remove(),
				db.collection('sh_user_playlist').where({device_id: deviceId}).remove(),
				db.collection('sh_device_share').where({device_id: deviceId}).remove()
			]);

			return {
				errCode: 0,
				errMsg: '设备删除成功'
			}
		} catch (error) {
			console.error('删除设备失败:', error);
			return {
				errCode: 'DELETE_DEVICE_FAILED',
				errMsg: '删除设备失败'
			}
		}
	},

	/**
	 * 更新设备状态
	 * @param {string} deviceId 设备ID
	 * @param {number} status 设备状态
	 * @param {object} currentPattern 当前图案信息
	 * @returns {object} 更新结果
	 */
	async updateDeviceStatus({deviceId, status, currentPattern}) {
		if (!deviceId || status === undefined) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			
			const updateData = {
				device_status: status,
				last_online_time: new Date(),
				update_time: new Date()
			};

			if (currentPattern) {
				updateData.current_pattern = currentPattern;
			}

			await db.collection('sh_user_device').doc(deviceId).update(updateData);

			return {
				errCode: 0,
				errMsg: '状态更新成功'
			}
		} catch (error) {
			console.error('更新设备状态失败:', error);
			return {
				errCode: 'UPDATE_STATUS_FAILED',
				errMsg: '更新设备状态失败'
			}
		}
	},

	/**
	 * 控制设备播放
	 * @param {string} deviceId 设备ID
	 * 
	 * @param {string} action 操作类型：play, pause, stop, next, prev
	 * @param {string} patternId 图案ID（可选）
	 * @returns {object} 控制结果
	 */
	async controlDevice({deviceId, command}) {

		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const userId = uid
		const action = command.action
		const patternId = command.patternId
		if (!deviceId || !userId || !action) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			const dbCmd = db.command;
			
			// 检查设备权限
			const deviceResult = await db.collection('sh_user_device').where(
				dbCmd.and([
					{_id: deviceId},
					dbCmd.or([
						{owner_id: userId},
						{shared_users: dbCmd.in([userId])}
					])
				])
			).get();

			if (deviceResult.data.length === 0) {
				return {
					errCode: 'NO_PERMISSION',
					errMsg: '无权限控制此设备'
				}
			}

			const device = deviceResult.data[0];

			// 获取播放列表
			const playlistResult = await db.collection('sh_user_playlist').where({
				device_id: deviceId
			}).get();

			if (playlistResult.data.length === 0) {
				return {
					errCode: 'PLAYLIST_NOT_FOUND',
					errMsg: '播放列表不存在'
				}
			}

			const playlist = playlistResult.data[0];
			let updateData = {};
			let deviceUpdateData = {};
			
			// 辅助函数：更新所有图案的播放状态
			const updatePlayingStatus = (patterns, playingPatternId) => {
				return patterns.map(p => ({
					...p,
					is_playing: p.pattern_id === playingPatternId
				}));
			};

			switch (action) {
				case 'play':
					if (patternId) {
						// 播放指定图案
						const patternResult = await db.collection('sh_pattern').doc(patternId).get();
						if (patternResult.data.length > 0) {
							const pattern = patternResult.data[0];
							deviceUpdateData.current_pattern = {
								pattern_id: patternId,
								pattern_name: pattern.pattern_name,
								progress: 0,
								status: 1
							};
							
							// 找到列表中对应的图案，并更新所有图案的播放状态
							const patternIndex = playlist.patterns.findIndex(p => p.pattern_id === patternId);
							if (patternIndex !== -1) {
								updateData.patterns = updatePlayingStatus(playlist.patterns, patternId);
								updateData.current_index = patternIndex;
							}
						}
					} else if (device.current_pattern) {
						// 继续播放当前图案
						deviceUpdateData.current_pattern = {
							...device.current_pattern,
							status: 1
						};
						
						// 更新当前播放图案的状态
						if (device.current_pattern.pattern_id) {
							updateData.patterns = updatePlayingStatus(playlist.patterns, device.current_pattern.pattern_id);
						}
					}
					break;

				case 'pause':
					if (device.current_pattern) {
						deviceUpdateData.current_pattern = {
							...device.current_pattern,
							status: 2
						};
						// 不清除播放标记，因为暂停状态仍然显示"播放中"
					}
					break;

				case 'stop':
					deviceUpdateData.current_pattern = {
						pattern_id: '',
						pattern_name: '',
						progress: 0,
						status: 0
					};
					// 清除所有图案的播放状态
					updateData.patterns = playlist.patterns.map(p => ({
						...p,
						is_playing: false
					}));
					break;

				case 'next':
					// 播放下一个图案
					if (playlist.patterns.length > 0) {
						const nextIndex = (playlist.current_index + 1) % playlist.patterns.length;
						const nextPattern = playlist.patterns[nextIndex];
						
						if (nextPattern) {
							const patternResult = await db.collection('sh_pattern').doc(nextPattern.pattern_id).get();
							if (patternResult.data.length > 0) {
								const pattern = patternResult.data[0];
								deviceUpdateData.current_pattern = {
									pattern_id: nextPattern.pattern_id,
									pattern_name: pattern.pattern_name,
									progress: 0,
									status: 1
								};
								updateData.current_index = nextIndex;
								// 更新所有图案的播放状态
								updateData.patterns = updatePlayingStatus(playlist.patterns, nextPattern.pattern_id);
							}
						}
					}
					break;

				case 'prev':
					// 播放上一个图案
					if (playlist.patterns.length > 0) {
						const prevIndex = playlist.current_index > 0 ? playlist.current_index - 1 : playlist.patterns.length - 1;
						const prevPattern = playlist.patterns[prevIndex];
						
						if (prevPattern) {
							const patternResult = await db.collection('sh_pattern').doc(prevPattern.pattern_id).get();
							if (patternResult.data.length > 0) {
								const pattern = patternResult.data[0];
								deviceUpdateData.current_pattern = {
									pattern_id: prevPattern.pattern_id,
									pattern_name: pattern.pattern_name,
									progress: 0,
									status: 1
								};
								updateData.current_index = prevIndex;
								// 更新所有图案的播放状态
								updateData.patterns = updatePlayingStatus(playlist.patterns, prevPattern.pattern_id);
							}
						}
					}
					break;
					
				case 'setPlayMode':
					// 设置播放模式
					const playMode = command.playMode;
					if (playMode !== undefined) {
						updateData.play_mode = playMode;
					}
					break;
					
				case 'clearPlaylist':
					// 清空播放列表
					updateData.patterns = [];
					updateData.current_index = 0;
					deviceUpdateData.current_pattern = {
						pattern_id: '',
						pattern_name: '',
						progress: 0,
						status: 0
					};
					break;
					
				case 'removePattern':
					// 从播放列表移除指定图案
					const patternIdToRemove = command.patternId;
					if (!patternIdToRemove) {
						return {
							errCode: 'PARAM_ERROR',
							errMsg: '图案ID不能为空'
						}
					}
					
					const patternIndex = playlist.patterns.findIndex(p => p.pattern_id === patternIdToRemove);
					if (patternIndex === -1) {
						return {
							errCode: 'PATTERN_NOT_FOUND',
							errMsg: '图案不在播放列表中'
						}
					}
					
					// 移除图案并调整索引
					const newPatterns = playlist.patterns.filter(p => p.pattern_id !== patternIdToRemove);
					
					// 如果删除的是当前播放项，需要更新设备当前播放状态
					if (patternIndex === playlist.current_index) {
						if (newPatterns.length > 0) {
							// 如果列表中还有图案，选择下一个或第一个播放
							const newIndex = Math.min(patternIndex, newPatterns.length - 1);
							updateData.current_index = newIndex;
							
							// 更新当前播放图案
							const nextPattern = newPatterns[newIndex];
							if (nextPattern) {
								const patternResult = await db.collection('sh_pattern').doc(nextPattern.pattern_id).get();
								if (patternResult.data.length > 0) {
									const pattern = patternResult.data[0];
									deviceUpdateData.current_pattern = {
										pattern_id: nextPattern.pattern_id,
										pattern_name: pattern.pattern_name,
										progress: 0,
										status: 1
									};
									// 更新播放状态
									updateData.patterns = updatePlayingStatus(newPatterns, nextPattern.pattern_id);
								}
							}
						} else {
							// 如果列表空了，清空当前播放状态
							updateData.current_index = 0;
							deviceUpdateData.current_pattern = {
								pattern_id: '',
								pattern_name: '',
								progress: 0,
								status: 0
							};
							updateData.patterns = newPatterns; // 空数组
						}
					} else if (patternIndex < playlist.current_index) {
						// 如果删除的是当前播放项之前的图案，需要调整当前索引
						updateData.current_index = playlist.current_index - 1;
						// 保持当前播放图案的播放状态
						const currentPlayingId = device.current_pattern?.pattern_id;
						updateData.patterns = updatePlayingStatus(newPatterns, currentPlayingId);
					} else {
						// 删除的是当前播放项之后的图案，当前索引不变
						const currentPlayingId = device.current_pattern?.pattern_id;
						updateData.patterns = updatePlayingStatus(newPatterns, currentPlayingId);
					}
					break;
					
				case 'reorderPatterns':
					// 重新排序播放列表
					const newOrderPatterns = command.patterns;
					if (!Array.isArray(newOrderPatterns)) {
						return {
							errCode: 'PARAM_ERROR',
							errMsg: '图案列表格式错误'
						}
					}
					
					// 保存当前播放的图案ID
					const currentPlayingPatternId = device.current_pattern?.pattern_id || '';
					
					// 更新所有图案的播放状态
					updateData.patterns = updatePlayingStatus(newOrderPatterns, currentPlayingPatternId);
					
					// 如果当前播放的图案ID还在列表中，更新索引
					if (currentPlayingPatternId) {
						const newCurrentIndex = newOrderPatterns.findIndex(p => p.pattern_id === currentPlayingPatternId);
						if (newCurrentIndex !== -1) {
							updateData.current_index = newCurrentIndex;
						} else if (newOrderPatterns.length > 0) {
							// 如果当前播放的图案不在新列表中，但列表不为空，选择第一个
							updateData.current_index = 0;
							const firstPattern = newOrderPatterns[0];
							const patternResult = await db.collection('sh_pattern').doc(firstPattern.pattern_id).get();
							if (patternResult.data.length > 0) {
								const pattern = patternResult.data[0];
								deviceUpdateData.current_pattern = {
									pattern_id: firstPattern.pattern_id,
									pattern_name: pattern.pattern_name,
									progress: 0,
									status: 1
								};
							}
						} else {
							// 列表为空
							updateData.current_index = 0;
							deviceUpdateData.current_pattern = {
								pattern_id: '',
								pattern_name: '',
								progress: 0,
								status: 0
							};
						}
					}
					break;

				default:
					return {
						errCode: 'INVALID_ACTION',
						errMsg: '无效的操作类型'
					}
			}

			// 更新数据
			const promises = [];
			
			if (Object.keys(updateData).length > 0) {
				updateData.update_time = new Date();
				promises.push(db.collection('sh_user_playlist').doc(playlist._id).update(updateData));
			}
			
			if (Object.keys(deviceUpdateData).length > 0) {
				deviceUpdateData.update_time = new Date();
				promises.push(db.collection('sh_user_device').doc(deviceId).update(deviceUpdateData));
			}

			await Promise.all(promises);

			// TODO: 这里应该向实际的IoT设备发送控制指令
			// 可以集成阿里云IoT、腾讯云IoT等服务

			return {
				errCode: 0,
				errMsg: '控制指令发送成功',
				data: {
					action,
					currentPattern: deviceUpdateData.current_pattern
				}
			}
		} catch (error) {
			console.error('控制设备失败:', error);
			return {
				errCode: 'CONTROL_DEVICE_FAILED',
				errMsg: '控制设备失败'
			}
		}
	},

	/**
	 * 获取设备详细信息
	 * @param {string} deviceId 设备ID
	 * @param {string} userId 用户ID
	 * @returns {object} 设备信息
	 */
	async getDeviceDetail({deviceId}) {
		const token = this.getUniIdToken()
		const uniID = UniID.createInstance({ context: this })
		const { code, uid, userInfo } = await uniID.checkToken(token)
		const userId = uid
		
		if (!deviceId || !userId) {
			return {
				errCode: 'PARAM_ERROR',
				errMsg: '参数不能为空'
			}
		}

		try {
			const db = uniCloud.database();
			const dbCmd = db.command;
			
			// 检查设备权限并获取设备信息
			const deviceResult = await db.collection('sh_user_device').where(
				dbCmd.and([
					{_id: deviceId},
					dbCmd.or([
						{owner_id: userId},
						{shared_users: dbCmd.in([userId])}
					])
				])
			).get();

			if (deviceResult.data.length === 0) {
				return {
					errCode: 'DEVICE_NOT_FOUND',
					errMsg: '设备不存在或无权限访问'
				}
			}

			const device = deviceResult.data[0];
			
			// 获取播放列表信息
			const playlistResult = await db.collection('sh_user_playlist').where({
				device_id: deviceId
			}).get();

			let playlist = null;
			if (playlistResult.data.length > 0) {
				playlist = playlistResult.data[0];
				
				// 确保每个图案都有播放状态
				if (playlist.patterns && playlist.patterns.length > 0) {
					const currentPatternId = device.current_pattern?.pattern_id || '';
					
					// 更新每个图案的播放状态
					playlist.patterns = playlist.patterns.map(pattern => ({
						...pattern,
						is_playing: pattern.pattern_id === currentPatternId
					}));
				}
			}

			return {
				errCode: 0,
				errMsg: '获取成功',
				data: {
					...device,
					playlist
				}
			}
		} catch (error) {
			console.error('获取设备详情失败:', error);
			return {
				errCode: 'GET_DEVICE_DETAIL_FAILED',
				errMsg: '获取设备详情失败'
			}
		}
	}
}
